// pages/waiting-query/waiting-query.js
Page({
  data: {
    patientInfo: {
      name: '',
      id: '',
      isSelf: true
    },
    appointmentInfo: {
      department: '消化内科-门诊3楼东区501',
      doctor: '赵马',
      queueNumber: '110'
    },
    queueInfo: {
      peopleAhead: 5
    },
    showPatientModal: false,
    patientList: []
  },

  onLoad(options) {
    // 页面加载时获取就诊人信息和候诊信息
    this.loadPatientInfo();
    this.loadQueueInfo();
  },

  // 加载就诊人信息
  loadPatientInfo() {
    wx.request({
      url: 'http://localhost:8005/patient/list',
      method: 'GET',
      header: { 'Content-Type': 'application/json' },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          let list = res.data
          if (typeof list === 'string') {
            try { list = JSON.parse(list) } catch (e) { return }
          }
          if (list.code !== undefined) list = list.data
          if (!Array.isArray(list)) return
          
          // 保存完整的就诊人列表
          const mapped = list.map(p => ({
            id: p.id,
            name: p.name,
            relation: p.relationTypeName || '本人',
            idNumber: (p.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
            isSelf: p.relationTypeName === '本人' || p.relationTypeName === undefined
          }))
          
          this.setData({ patientList: mapped })
          
          // 找到默认就诊人
          const defaultPatient = list.find(p => p.isDefault === 1)
          if (defaultPatient) {
            this.setData({
              patientInfo: {
                name: defaultPatient.name,
                id: (defaultPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
                isSelf: defaultPatient.relationTypeName === '本人' || defaultPatient.relationTypeName === undefined
              }
            })
          } else {
            // 如果没有默认就诊人，使用第一个就诊人
            const firstPatient = list[0]
            if (firstPatient) {
              this.setData({
                patientInfo: {
                  name: firstPatient.name,
                  id: (firstPatient.idCardNumber || '').replace(/(\w{3})\w+(\w{2})/, '$1********$2'),
                  isSelf: firstPatient.relationTypeName === '本人' || firstPatient.relationTypeName === undefined
                }
              })
            }
          }
        }
      }
    })
  },

  // 加载排队信息
  loadQueueInfo() {
    wx.showLoading({
      title: '加载中...'
    });

    // 模拟API调用
    setTimeout(() => {
      wx.hideLoading();
      
      // 模拟数据更新
      this.setData({
        'queueInfo.peopleAhead': Math.floor(Math.random() * 10) + 1
      });
    }, 1000);
  },

  // 切换就诊人
  switchPatient() {
    this.setData({
      showPatientModal: true
    });
  },

  // 关闭选择就诊人模态框
  closePatientModal() {
    this.setData({
      showPatientModal: false
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 选择患者
  selectPatient(e) {
    const patient = e.currentTarget.dataset.patient;
    
    this.setData({
      'patientInfo.name': patient.name,
      'patientInfo.id': patient.idNumber,
      'patientInfo.isSelf': patient.isSelf,
      showPatientModal: false
    });

    // 保存到本地存储
    const cacheUser = wx.getStorageSync('userInfo') || {}
    wx.setStorageSync('userInfo', { ...cacheUser, patientId: patient.id })

    wx.showToast({
      title: `已切换到${patient.name}`,
      icon: 'success'
    });

    // 重新加载排队信息
    this.loadQueueInfo();
  },

  // 更新排队信息
  updateQueue() {
    wx.showLoading({
      title: '更新中...'
    });

    // 模拟API调用
    setTimeout(() => {
      wx.hideLoading();
      
      // 模拟数据更新
      const newPeopleAhead = Math.floor(Math.random() * 10) + 1;
      this.setData({
        'queueInfo.peopleAhead': newPeopleAhead
      });

      wx.showToast({
        title: '更新成功',
        icon: 'success'
      });
    }, 1500);
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1
    });
  }
});
